package com.flink.demo.wordcount04;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * description
 *
 * @author zsyoung@qq.com
 * 2020/7/4 0:44
 */
public class WordCountDataSet {
    public static void main(String[] args) throws Exception {
        //1、创建上下文环境
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //2、创建对象
        DataSet<String> text = env.fromElements(
                "flink spark storm",
                "flink SPARK storm",
                "storm spark storm",
                "spark spark spark",
                "storm STORM storm"
        );
        //4、计算
        DataSet<Tuple2<String, Integer>> counts =
                text.flatMap(new LineSplitter())
                        .groupBy(0)
                        .sum(1);
        //5、打印
        counts.printToErr();
    }


    //3、对象拆分类
    public static class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> {

        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] split = value.toLowerCase().split("\\W+");
            for (String s : split) {
                if (s.length() > 0) {
                    collector.collect(new Tuple2<String, Integer>(s, 1));
                }
            }

        }
    }
}


